from fastapi import APIRouter, HTTPException, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, func, desc
from typing import List, Optional
from datetime import date, datetime
from database import get_db, DBBookBorrow
from models import (
    BookBorrowCreate, BookBorrowResponse, BookBorrowListResponse, 
    BookBorrowStats, BorrowStatus, APIResponse
)
from auth import get_current_user, get_current_admin_user

router = APIRouter()

@router.get("/", response_model=BookBorrowListResponse)
async def get_book_borrow_data(
    borrower: Optional[str] = Query(None, description="借阅者姓名"),
    borrowed_book: Optional[str] = Query(None, description="图书名称"),
    borrow_status: Optional[BorrowStatus] = Query(None, description="借阅状态"),
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小"),
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取图书借阅数据列表"""
    
    # 构建查询条件
    query = db.query(DBBookBorrow)
    
    if borrower:
        query = query.filter(DBBookBorrow.borrower.contains(borrower))
    
    if borrowed_book:
        query = query.filter(DBBookBorrow.borrowed_book.contains(borrowed_book))
    
    if borrow_status:
        query = query.filter(DBBookBorrow.borrow_status == borrow_status)
    
    if start_date:
        query = query.filter(DBBookBorrow.borrow_date >= start_date)
    
    if end_date:
        query = query.filter(DBBookBorrow.borrow_date <= end_date)
    
    # 获取总数
    total = query.count()
    
    # 分页和排序
    borrow_data = query.order_by(desc(DBBookBorrow.borrow_date), desc(DBBookBorrow.id))\
                       .offset((page - 1) * page_size)\
                       .limit(page_size)\
                       .all()
    
    # 计算总页数
    total_pages = (total + page_size - 1) // page_size
    
    return BookBorrowListResponse(
        data=[BookBorrowResponse(
            id=item.id,
            borrow_date=item.borrow_date,
            borrower=item.borrower,
            borrowed_book=item.borrowed_book,
            book_unit_price=item.book_unit_price,
            borrow_status=item.borrow_status,
            created_at=item.created_at
        ) for item in borrow_data],
        total=total,
        page=page,
        page_size=page_size,
        total_pages=total_pages
    )

@router.post("/", response_model=BookBorrowResponse)
async def create_book_borrow_data(
    borrow_data: BookBorrowCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_admin_user)  # 只有管理员可以添加数据
):
    """添加图书借阅数据"""
    
    # 创建新的图书借阅数据
    db_borrow = DBBookBorrow(
        borrow_date=borrow_data.borrow_date,
        borrower=borrow_data.borrower,
        borrowed_book=borrow_data.borrowed_book,
        book_unit_price=borrow_data.book_unit_price,
        borrow_status=borrow_data.borrow_status
    )
    
    db.add(db_borrow)
    db.commit()
    db.refresh(db_borrow)
    
    return BookBorrowResponse(
        id=db_borrow.id,
        borrow_date=db_borrow.borrow_date,
        borrower=db_borrow.borrower,
        borrowed_book=db_borrow.borrowed_book,
        book_unit_price=db_borrow.book_unit_price,
        borrow_status=db_borrow.borrow_status,
        created_at=db_borrow.created_at
    )

@router.delete("/{borrow_id}", response_model=APIResponse)
async def delete_book_borrow_data(
    borrow_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_admin_user)  # 只有管理员可以删除数据
):
    """删除图书借阅数据"""
    
    borrow_data = db.query(DBBookBorrow).filter(DBBookBorrow.id == borrow_id).first()
    
    if not borrow_data:
        raise HTTPException(status_code=404, detail="图书借阅数据不存在")
    
    db.delete(borrow_data)
    db.commit()
    
    return APIResponse(
        success=True,
        message="图书借阅数据删除成功"
    )

@router.get("/borrowers", response_model=List[str])
async def get_borrowers(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取所有借阅者列表"""
    
    borrowers = db.query(DBBookBorrow.borrower).distinct().all()
    return [borrower[0] for borrower in borrowers]

@router.get("/books", response_model=List[str])
async def get_books(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取所有图书列表"""
    
    books = db.query(DBBookBorrow.borrowed_book).distinct().all()
    return [book[0] for book in books]

@router.get("/stats", response_model=BookBorrowStats)
async def get_book_borrow_stats(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取图书借阅数据统计信息"""
    
    # 总记录数
    total_records = db.query(DBBookBorrow).count()
    
    # 借阅者数量
    total_borrowers = db.query(DBBookBorrow.borrower).distinct().count()
    
    # 图书数量
    total_books = db.query(DBBookBorrow.borrowed_book).distinct().count()
    
    # 平均价格
    avg_price_result = db.query(func.avg(DBBookBorrow.book_unit_price)).scalar()
    average_price = round(avg_price_result, 2) if avg_price_result else 0
    
    # 今日新增记录
    today = date.today()
    today_records = db.query(DBBookBorrow).filter(
        func.date(DBBookBorrow.created_at) == today
    ).count()
    
    # 最近10条数据
    recent_data = db.query(DBBookBorrow).order_by(desc(DBBookBorrow.created_at)).limit(10).all()
    
    return BookBorrowStats(
        total_records=total_records,
        total_borrowers=total_borrowers,
        total_books=total_books,
        average_price=average_price,
        today_records=today_records,
        recent_data=[BookBorrowResponse(
            id=item.id,
            borrow_date=item.borrow_date,
            borrower=item.borrower,
            borrowed_book=item.borrowed_book,
            book_unit_price=item.book_unit_price,
            borrow_status=item.borrow_status,
            created_at=item.created_at
        ) for item in recent_data]
    )

@router.get("/statuses", response_model=List[str])
async def get_borrow_statuses():
    """获取所有借阅状态"""
    return [status.value for status in BorrowStatus] 